import { Data, Version, Plugin_Name } from '../index.js'
import fs from 'fs'
import puppeteer from '../../../../lib/puppeteer/puppeteer.js'

const _path = process.cwd()

export default async function (path, params, cfg) {
  let [app, tpl] = path.split('/')
  let { e } = cfg
  let layoutPath = `${_path}/plugins/${Plugin_Name}/resources/common/layout/`
  let resPath = `../../../../../plugins/${Plugin_Name}/resources/`
  
  Data.createDir(`data/html/${Plugin_Name}/${app}/${tpl}`, 'root')
  
  let data = {
    ...params,
    _plugin: Plugin_Name,
    saveId: params.saveId || params.save_id || tpl,
    tplFile: `./plugins/${Plugin_Name}/resources/${app}/${tpl}.html`,
    pluResPath: resPath,
    _res_path: resPath,
    _layout_path: layoutPath,
    _tpl_path: `${_path}/plugins/${Plugin_Name}/resources/common/tpl/`,
    defaultLayout: `${layoutPath}default.html`,
    elemLayout: `${layoutPath}elem.html`,
    pageGotoParams: {
      waitUntil: 'networkidle0'
    },
    sys: {
      scale: 1,
      copyright: `喵崽<span class="version">${Version.yunzai}</span> &nbsp bilibili-plugin<span class="version">${Version.ver}</span>`
    },
    quality: 100,
    _app: app // 此属性在后续需要用到
  }
  
  // 添加错误处理
  try {
    if (process.argv.includes('web-debug')) {
      let saveDir = `${_path}/data/ViewData/`
      
      if (!fs.existsSync(saveDir)) {
        fs.mkdirSync(saveDir)
      }
      
      let file = `${saveDir}${tpl}.json`
      fs.writeFileSync(file, JSON.stringify(data))
    }
    
    let base64 = await puppeteer.screenshot(`${Plugin_Name}/${app}/${tpl}`, data)
    
    if (base64) {
      if (path === 'yy/lb') {
        return await e.reply(base64, false, { recallMsg: 60 }) && !cfg.retMsgId;
      }
      return await e.reply(base64) && !cfg.retMsgId;
    }
  } catch (error) {
    console.error('处理过程中出现错误:', error);
    throw new Error('渲染失败，请检查输入和配置。');
  }
  
  return true;
}
